package com.ad.pet.app.photo;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ProgressBar;

import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.ad.pet.R;
import com.ad.pet.app.photo.model.ImageItem;
import com.ad.pet.common.data.utils.SnackBarUtil;
import com.ad.pet.common.data.utils.glide.GlideUtil;
import com.ad.pet.common.data.utils.ui.LayoutInflaterUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.AppToolbarActivity;
import com.ad.pet.common.structure.ui.control.HackyViewPager;
import com.github.chrisbanes.photoview.PhotoView;

import java.util.ArrayList;

import javax.inject.Inject;

public class PhotoMaxListSelectActivity extends AppToolbarActivity {

    @Inject
    ToastUtil mToastUtil;
    private HackyViewPager mViewPager;
    private ArrayList<ImageItem> mPhotoItems;
    private CheckBox mCbOrigin;
    private CheckBox mCbSelect;
    private ImageItem mImageItem;
    private int mCurrentPosition;
    private int mSelectedMax;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mStatusLayoutManager.showContent();
        mToolbar.setNextOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送图片
                if (getSelectCount() == 0) {
                    mToastUtil.showShort(getString(R.string.please_chose_last_one_photo));
                    return;
                }
                back(1);
            }
        });
        mToolbar.setBackOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                back(0);
            }
        });
        setNextText();
        setTitle(mCurrentPosition);
    }


    public int getSelectCount() {
        if (mPhotoItems == null) {
            return 0;
        }
        int count = 0;
        for (ImageItem photoItem : mPhotoItems) {
            if (photoItem.isSelected()) {
                count++;
            }
        }
        return count;
    }

    public void setNextText() {
        if (mToolbar == null) return;
        int selectCount = getSelectCount();
        if (selectCount > 0) {
            mToolbar.setNextText(String.format("Send(%d)", selectCount));
        } else {
            mToolbar.setNextText("Send");
        }
    }

    public void setTitle(int index) {
        if (mToolbar == null) return;
        String title = "NO DATAS";
        if (mPhotoItems != null) {
            title = String.format("%d/%d", index + 1, mPhotoItems.size());
        }
        mToolbar.setTitle(title);
    }

    @Override
    protected void initData() {
        mPhotoItems = getIntent().getParcelableArrayListExtra("photos");
        mSelectedMax = getIntent().getIntExtra("selectedMax", 1);
        mCurrentPosition = getIntent().getIntExtra("currentPosition", 0);
        if (mPhotoItems == null) {
            mPhotoItems = new ArrayList<>();
        }
    }


    @Override
    protected void initEvents() {
        mViewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return mPhotoItems == null ? 0 : mPhotoItems.size();
            }

            @Override
            public Object instantiateItem(final ViewGroup container, final int position) {
                View view = LayoutInflaterUtil.inflater(R.layout.activity_photo_max_list_select, container, false);
                PhotoView photoview = (PhotoView) view.findViewById(R.id.photo_view);
                final ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
                final ImageItem imageItem = mPhotoItems.get(position);
                loadImage(container, photoview, imageItem.getImagePath(), imageItem.getImagePath(), progressBar);
                container.addView(view);
                return view;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }
        });
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setTitle(position);
                mImageItem = mPhotoItems.get(position);
                mCbSelect.setChecked(mImageItem.isSelected());
                mCbOrigin.setChecked(mImageItem.isOriginal());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mCbSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!mImageItem.isSelected() && isChecked && mPhotoItems.size() == mSelectedMax) {
                    mToastUtil.showShort("MOST:" + mSelectedMax );
                    return;
                }
                mImageItem.setSelected(isChecked);
                setNextText();
            }
        });
        mCbOrigin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mImageItem.setOriginal(isChecked);
            }
        });
        mViewPager.setCurrentItem(mCurrentPosition);
    }

    private void loadImage(final ViewGroup container, final PhotoView photoview, final String originUrl, final String compressUrl, final ProgressBar progressBar) {
        GlideUtil.loadThumbnailAddListener(container.getContext()
                , compressUrl, originUrl
                , photoview, new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        SnackBarUtil.showStatic(container, "图片加载失败，是否重试?", "重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                loadImage(container, photoview, originUrl, compressUrl, progressBar);
                            }
                        });
                        progressBar.setVisibility(View.GONE);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        progressBar.setVisibility(View.GONE);
                        return false;
                    }
                });
    }


    @Override
    protected void initViews() {
        mViewPager = (HackyViewPager) findViewById(R.id.vp_view);
        findViewById(R.id.layout_bottom_bar).setVisibility(View.VISIBLE);
        mCbOrigin = (CheckBox) findViewById(R.id.cb_origin);
        mCbSelect = (CheckBox) findViewById(R.id.cb_select);

    }

    @Override
    public void initInject() {
//        DaggerChatComponent.builder().activityModule(getActivityModule()).applicationComponent(getApplicationComponent()).build().inject(this);
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_photo_max_list;
    }

    @Override
    public void onBackPressed() {
        back(0);
    }

    public void back(int send) {
        Intent intent = new Intent();
        intent.putExtra("send", send);
        intent.putExtra("path", mPhotoItems);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected void clickRetry(View v) {

    }

    protected BasePresenter getPresenter() {
        return null;
    }

}
